import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {
      username: '123',
      password: '123123',
      registerDate: '2023-01-01',
      courses: 'Vue.js入门课程, Element UI实战'
    },
    orders: [
      {
        id: '20230001',
        course: 'Vue.js入门课程',
        price: '¥199',
        status: '已完成',
        date: '2023-01-15'
      },
      {
        id: '20230002',
        course: 'Element UI实战',
        price: '¥299',
        status: '待支付',
        date: '2023-01-16'
      }
    ],
    // 存储用户已购买的课程信息
    purchasedCourses: [
      {
        id: 1,
        name: 'Vue.js入门课程',
        purchaseDate: '2023-01-15'
      }
    ]
  },
  getters: {
    // 检查课程是否已购买
    isCourseAlreadyPurchased: (state) => (courseId) => {
      return state.purchasedCourses.some(course => Number(course.id) === Number(courseId));
    },
    // 获取已完成支付的订单对应的课程
    completedCourses: (state) => {
      // 找出已完成的订单
      const completedOrders = state.orders.filter(order => order.status === '已完成');
      // 从所有课程中找出已完成订单对应的课程
      return completedOrders.map(order => {
        return {
          name: order.course,
          orderId: order.id,
          purchaseDate: order.date
        };
      });
    }
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    ADD_ORDER(state, order) {
      state.orders.unshift(order);
    },
    DELETE_ORDER(state, orderId) {
      state.orders = state.orders.filter(order => order.id !== orderId);
    },
    UPDATE_ORDER_STATUS(state, {id, status}) {
      const order = state.orders.find(o => o.id === id);
      if (order) {
        order.status = status;
        
        // 如果订单状态变为"已完成"，添加到已购买课程列表
        if (status === '已完成') {
          // 查找对应的课程ID
          const courseMatch = /(\d+)/.exec(order.course);
          if (courseMatch) {
            const courseId = parseInt(courseMatch[1]);
            
            // 检查是否已存在于已购买列表
            if (!state.purchasedCourses.some(c => c.id === courseId)) {
              state.purchasedCourses.push({
                id: courseId,
                name: order.course,
                purchaseDate: order.date
              });
            }
          }
        }
      }
    },
    ADD_PURCHASED_COURSE(state, course) {
      // 避免重复添加
      if (!state.purchasedCourses.some(c => c.id === course.id)) {
        state.purchasedCourses.push(course);
      }
    }
  },
  actions: {
    addOrder({ commit }, order) {
      commit('ADD_ORDER', order);
    },
    deleteOrder({ commit }, orderId) {
      commit('DELETE_ORDER', orderId);
    },
    updateOrderStatus({ commit }, payload) {
      commit('UPDATE_ORDER_STATUS', payload);
    },
    addPurchasedCourse({ commit }, course) {
      commit('ADD_PURCHASED_COURSE', course);
    }
  }
})